package com.yuyou.fn.crm.service.impl;

import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.*;
import com.yuyou.fn.crm.entity.CrmCommunicateHistory;
import com.yuyou.fn.crm.entity.CrmStudentCommunicate;
import com.yuyou.fn.crm.mapper.CrmCommunicateHistoryMapper;
import com.yuyou.fn.crm.service.ICrmCommunicateHistoryService;
import com.yuyou.fn.crm.service.ICrmStudentCommunicateService;
import com.yuyou.fn.crm.vo.CrmCommunicateHistoryQueryVo;
import com.yuyou.fn.crm.vo.CrmCommunicateHistorySaveVo;
import com.yuyou.fn.crm.vo.CrmCommunicateInputVo;
import com.yuyou.fn.educational.entity.BaseGrade;
import com.yuyou.fn.educational.entity.Student;
import com.yuyou.fn.educational.entity.Teacher;
import com.yuyou.fn.educational.service.IBaseGradeService;
import com.yuyou.fn.educational.service.IStudentService;
import com.yuyou.fn.educational.service.ITeacherService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * CrmCommunicateHistory 表数据服务层接口实现类
 */
@Service
public class CrmCommunicateHistoryServiceImpl extends SuperServiceImpl<CrmCommunicateHistoryMapper, CrmCommunicateHistory, Long> implements ICrmCommunicateHistoryService {

    @Resource
    private ICrmStudentCommunicateService crmStudentCommunicateService;

    @Resource
    private ITeacherService teacherService;

    @Resource
    private IStudentService studentService;

    @Resource
    private IBaseGradeService baseGradeService;

    @Override
    @Transactional
    public void saveCommunicateHistory(CrmCommunicateHistorySaveVo crmCommunicateHistorySaveVo) {
        Principals.Principal principal = Principals.get();
        if (principal == null) {
            throw new BusException("请登录");
        }

        Teacher teacher = teacherService.findById(principal.id);

        if (teacher == null) {
            throw new BusException("查不到该老师");
        }

        CrmStudentCommunicate studentCommunicate = crmStudentCommunicateService.findById(crmCommunicateHistorySaveVo.getStudentCommunicateId());
        CrmStudentCommunicate updateCrmStudentCommunicate = new CrmStudentCommunicate();
        updateCrmStudentCommunicate.setStudentCommunicateId(studentCommunicate.getStudentCommunicateId());
        updateCrmStudentCommunicate.setCommunicateNum(studentCommunicate.getCommunicateNum() + 1);
        updateCrmStudentCommunicate.setFocusOn(crmCommunicateHistorySaveVo.getFocusOn());
        updateCrmStudentCommunicate.setCommunicateDate(crmCommunicateHistorySaveVo.getCommunicateDate());
        updateCrmStudentCommunicate.setNextCommunicateDate(crmCommunicateHistorySaveVo.getNextCommunicateDate());
        updateCrmStudentCommunicate.setCommunicateState(1);
        crmStudentCommunicateService.updateSelectiveById(updateCrmStudentCommunicate);
        Student student = studentService.findById(studentCommunicate.getStudentId());
        CrmCommunicateHistory crmCommunicateHistory = new CrmCommunicateHistory();
        BeanUtils.copyProperties(crmCommunicateHistory, crmCommunicateHistorySaveVo);
        crmCommunicateHistory.setOperatorId(principal.id);
        crmCommunicateHistory.setUpdateTime(TimeUtils.now());
        crmCommunicateHistory.setCreateTime(TimeUtils.now());
        crmCommunicateHistory.setStudentName(student.getName());
        crmCommunicateHistory.setStudentPhoneNo(student.getPhoneNo());
        crmCommunicateHistory.setStudentNo(student.getStudentNo());
        crmCommunicateHistory.setSeniorId(teacher.getTeacherId());
        crmCommunicateHistory.setSeniorName(teacher.getTeacherName());
        crmCommunicateHistory.setStudentId(studentCommunicate.getStudentId());
        crmCommunicateHistory.setPeriodId(studentCommunicate.getPeriodId());
        crmCommunicateHistory.setBusTeamId(studentCommunicate.getBusTeamId());
        crmCommunicateHistory.setBusTeamName(studentCommunicate.getBusTeamName());
        crmCommunicateHistory.setPeriodName(studentCommunicate.getPeriodName());
        crmCommunicateHistory.setGradeId(studentCommunicate.getGradeId());
        crmCommunicateHistory.setSegmentNo(studentCommunicate.getSegmentNo());
        crmCommunicateHistory.setStudentState(studentCommunicate.getStudentState());
        this.insert(crmCommunicateHistory);

    }

    @Override
    @Transactional
    public void saveCommunicateHistoryBatch(List<CrmCommunicateInputVo> crmCommunicateInputVos) {

        Principals.Principal principal = Principals.get();
        if (principal == null) {
            throw new BusException("请登录");
        }

        Teacher teacher = teacherService.findById(principal.id);

        if (teacher == null) {
            throw new BusException("查不到该老师");
        }

        List<CrmStudentCommunicate> updatecrmStudentCommunicates = new ArrayList<>();
        List<CrmCommunicateHistory> insertcrmCommunicateHistories = new ArrayList<>();
        Map<Long, CrmStudentCommunicate> communicateMap = getCrmStudentCommunicate(crmCommunicateInputVos);
        for (CrmCommunicateInputVo crmCommunicateInputVo : crmCommunicateInputVos) {
            checkInput(crmCommunicateInputVo);
            Long studentCommunicateId = crmCommunicateInputVo.getStudentCommunicateId();
            CrmStudentCommunicate databaseCrmStudentCommunicate = communicateMap.get(studentCommunicateId);
            if(null == databaseCrmStudentCommunicate){
                throw new BusException("唯一ID有误，请重新下载模板！");
            }
            CrmStudentCommunicate updateCrmStudentCommunicate = new CrmStudentCommunicate();
            updateCrmStudentCommunicate.setStudentCommunicateId(studentCommunicateId);
            updateCrmStudentCommunicate.setCommunicateNum(databaseCrmStudentCommunicate.getCommunicateNum() + 1);
            updateCrmStudentCommunicate.setFocusOn(crmCommunicateInputVo.getFocusOnName().equals("是") ? 1 : 0);
            Date communicateDate = crmCommunicateInputVo.getCommunicateDate();
            Date nextCommunicateDate = crmCommunicateInputVo.getNextCommunicateDate();
            updateCrmStudentCommunicate.setCommunicateDate(communicateDate);
            updateCrmStudentCommunicate.setNextCommunicateDate(nextCommunicateDate);
            updateCrmStudentCommunicate.setCommunicateState(1);
            updatecrmStudentCommunicates.add(updateCrmStudentCommunicate);

            CrmCommunicateHistory insertCrmCommunicateHistory = new CrmCommunicateHistory();
            fillCrmCommunicateHistory(insertCrmCommunicateHistory, crmCommunicateInputVo);
            insertCrmCommunicateHistory.setStudentCommunicateId(studentCommunicateId);
            insertCrmCommunicateHistory.setOperatorId(principal.id);
            insertCrmCommunicateHistory.setUpdateTime(TimeUtils.now());
            insertCrmCommunicateHistory.setCreateTime(TimeUtils.now());
            insertCrmCommunicateHistory.setStudentName(databaseCrmStudentCommunicate.getStudentName());
            insertCrmCommunicateHistory.setStudentPhoneNo(databaseCrmStudentCommunicate.getStudentPhoneNo());
            insertCrmCommunicateHistory.setStudentNo(databaseCrmStudentCommunicate.getStudentNo());
            insertCrmCommunicateHistory.setSeniorId(teacher.getTeacherId());
            insertCrmCommunicateHistory.setSeniorName(teacher.getTeacherName());
            insertCrmCommunicateHistory.setStudentId(databaseCrmStudentCommunicate.getStudentId());
            insertCrmCommunicateHistory.setPeriodId(databaseCrmStudentCommunicate.getPeriodId());
            insertCrmCommunicateHistory.setBusTeamId(databaseCrmStudentCommunicate.getBusTeamId());
            insertCrmCommunicateHistory.setBusTeamName(databaseCrmStudentCommunicate.getBusTeamName());
            insertCrmCommunicateHistory.setPeriodName(databaseCrmStudentCommunicate.getPeriodName());
            insertCrmCommunicateHistory.setGradeId(databaseCrmStudentCommunicate.getGradeId());
            insertCrmCommunicateHistory.setSegmentNo(databaseCrmStudentCommunicate.getSegmentNo());
            insertCrmCommunicateHistory.setStudentState(databaseCrmStudentCommunicate.getStudentState());
            insertCrmCommunicateHistory.setCommunicateDate(communicateDate);
            insertCrmCommunicateHistory.setNextCommunicateDate(nextCommunicateDate);
            insertcrmCommunicateHistories.add(insertCrmCommunicateHistory);
        }

        crmStudentCommunicateService.updateCrmStudentCommunicateBatch(updatecrmStudentCommunicates);
        this.insertBatch(insertcrmCommunicateHistories);
    }

    private void checkInput(CrmCommunicateInputVo crmCommunicateInputVo) {
        if (crmCommunicateInputVo.getWayName() == null || crmCommunicateInputVo.getContinueReadName() == null ||
                crmCommunicateInputVo.getFocusOnName() == null || crmCommunicateInputVo.getCommunicateDate() == null
                || crmCommunicateInputVo.getCommunicateContent() == null) {
            throw new BusException("有必填项为空！");
        }
    }

    private static Map<String, Integer> wayMap = new HashMap<>();
    private static Map<String, Integer> continueReadMap = new HashMap<>();
    private static Map<String, Integer> focusOnMap = new HashMap<>();

    static {
        wayMap.put("电话拨入", 0);
        wayMap.put("电话拨出", 1);
        wayMap.put("面谈", 2);
        wayMap.put("微信/QQ", 3);
        wayMap.put("其他", 4);

        continueReadMap.put("强烈", 0);
        continueReadMap.put("一般", 1);
        continueReadMap.put("无意愿", 2);

        focusOnMap.put("否", 0);
        focusOnMap.put("是", 1);
    }

    /**
     * 填充导入的内容
     *
     * @param crmCommunicateHistory
     * @param crmCommunicateInputVo
     */
    private void fillCrmCommunicateHistory(CrmCommunicateHistory crmCommunicateHistory, CrmCommunicateInputVo crmCommunicateInputVo) {
        crmCommunicateHistory.setWay(wayMap.get(crmCommunicateInputVo.getWayName().trim()));
        crmCommunicateHistory.setContinueRead(continueReadMap.get(crmCommunicateInputVo.getContinueReadName().trim()));
        crmCommunicateHistory.setFocusOn(focusOnMap.get(crmCommunicateInputVo.getFocusOnName().trim()));
        crmCommunicateHistory.setCommunicateContent(crmCommunicateInputVo.getCommunicateContent());
    }

    public Map<Long, CrmStudentCommunicate> getCrmStudentCommunicate(List<CrmCommunicateInputVo> crmCommunicateInputVos) {
        List<Long> studentComunicateIds = BeanUtils.toList(crmCommunicateInputVos, "studentCommunicateId");
        List<CrmStudentCommunicate> crmStudentCommunicateList = crmStudentCommunicateService.findByIds(studentComunicateIds);
        Map<Long, CrmStudentCommunicate> communicateMap = BeanUtils.toMap(crmStudentCommunicateList, "studentCommunicateId");
        return communicateMap;
    }


    @Override
    public List<CrmCommunicateHistory> findCommunicateHistoryList(CrmCommunicateHistoryQueryVo crmCommunicateHistoryQueryVo) {
        Example<CrmCommunicateHistory> crmCommunicateHistoryExample = CrmCommunicateHistory.createExample();
        Example.Criteria criteria = crmCommunicateHistoryExample.createCriteria();
        CriteriaUtils.fillCondition(criteria, crmCommunicateHistoryQueryVo);
        crmCommunicateHistoryExample.orderBy("createTime").desc();
        return findListByExample(crmCommunicateHistoryExample);
    }

    @Override
    public Page<CrmCommunicateHistory> findCommunicateHistoryPage(CrmCommunicateHistoryQueryVo crmCommunicateHistoryQueryVo, int pageNo, int pageSize) {
        Example<CrmCommunicateHistory> crmCommunicateHistoryExample = CrmCommunicateHistory.createExample();
        Example.Criteria criteria = crmCommunicateHistoryExample.createCriteria();
        CriteriaUtils.fillCondition(criteria, crmCommunicateHistoryQueryVo);
        crmCommunicateHistoryExample.orderBy("createTime").desc();
        return findPageByExample(crmCommunicateHistoryExample, pageNo, pageSize);
    }

    @Override
    public SXSSFWorkbook exportCommunicateHistory(CrmCommunicateHistoryQueryVo crmCommunicateHistoryQueryVo) {
        Page<CrmCommunicateHistory> page = this.findCommunicateHistoryPage(crmCommunicateHistoryQueryVo, 1, 30000);
        List<BaseGrade> baseGradeList = baseGradeService.findAllFromCache();
        Map<Long, BaseGrade> map = BeanUtils.toMap(baseGradeList, "gradeId");
        return communicateHistory2excel(page.getRecords(), map);
    }

    public static SXSSFWorkbook communicateHistory2excel(List<CrmCommunicateHistory> crmCommunicateHistoryList, Map<Long, BaseGrade> map) {

        SXSSFWorkbook excel = new SXSSFWorkbook();
        SXSSFSheet sheet = excel.createSheet("家校沟通");
        SXSSFRow firstRow = sheet.createRow(0);
        String[] titles = new String[]{"学生姓名", "学生电话", "学号", "报读期数", "生源类型","报读年级","段次","报读业务组", "班主任", "沟通时间", "沟通内容"};
        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }
        int rowNum = 1;

        if (crmCommunicateHistoryList != null) {
            for (CrmCommunicateHistory crmCommunicateHistory : crmCommunicateHistoryList) {
                int cellNum = 0;

                SXSSFRow row = sheet.createRow(rowNum++);

                SXSSFCell cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmCommunicateHistory.getStudentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmCommunicateHistory.getStudentPhoneNo()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmCommunicateHistory.getStudentNo()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmCommunicateHistory.getPeriodName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(crmCommunicateHistory.getStudentState() == null ? "" : crmCommunicateHistory.getStudentState() == 0 ? "新生" : crmCommunicateHistory.getStudentState() == 1 ? "老生" : "续读生");


                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(map.get(crmCommunicateHistory.getGradeId()) == null ? "" : map.get(crmCommunicateHistory.getGradeId()).getGradeName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(crmCommunicateHistory.getSegmentNo() == null ? "" : crmCommunicateHistory.getSegmentNo().toString());


                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmCommunicateHistory.getBusTeamName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmCommunicateHistory.getSeniorName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(crmCommunicateHistory.getCommunicateDate() == null ? "" : Utils.formatDate(crmCommunicateHistory.getCommunicateDate(), "yyyy-MM-dd"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmCommunicateHistory.getCommunicateContent()));
            }
        }

        return excel;
    }


    @Override
    public List<CrmCommunicateHistory> findCommunicateHistoryByCommunicateIds(List<Long> studentCommunicateIds) {
        Example<CrmCommunicateHistory> crmCommunicateHistoryExample = CrmCommunicateHistory.createExample();
        Example.Criteria criteria = crmCommunicateHistoryExample.createCriteria();
        criteria.andIn("studentCommunicateId", studentCommunicateIds);
        crmCommunicateHistoryExample.orderBy("createTime").desc();
        return findListByExample(crmCommunicateHistoryExample);
    }
}